package com.example.myapplication1;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.os.Build;
import android.os.Bundle;
import android.os.SystemClock;
import android.text.Html;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Toolbar;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.alimt.model.v20181012.TranslateGeneralRequest;
import com.aliyuncs.alimt.model.v20181012.TranslateGeneralResponse;
import com.aliyuncs.auth.AcsURLEncoder;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.example.myapplication1.adapter.FruitAdapter;
import com.example.myapplication1.baidudemo.MD5;
import com.example.myapplication1.bean.Fruit;
import com.example.myapplication1.diyview.NoPaddingTextView;
import com.google.gson.Gson;


import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SimpleTimeZone;
import java.util.UUID;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

import Decoder.BASE64Encoder;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class MainActivity extends AppCompatActivity {

    private NoPaddingTextView NoPaddingTextView;
    private RecyclerView recycleview;
    private List<Fruit> fruitList = new ArrayList<>();
    private ImageView img_shaderbg;
    private LinearLayout ll_test;
    private RelativeLayout rl_root;
    private ImageView img_photo;
    private LinearLayout ll_contaier;
    private Button btn_test_setY;
    private int count = 0;
    private float mInitY;
    private float mLastMotionY;

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        View
                rl_root = findViewById(R.id.rl_root);
        recycleview = findViewById(R.id.recycleview);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
//        GridLayoutManager gridLayoutManager = new GridLayoutManager(this,3);
//        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
//            @Override
//            public int getSpanSize(int position) {
//
//                return position==0?3:1;
//            }
//        });
        recycleview.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getBaseContext(), "1111111", Toast.LENGTH_SHORT).show();
            }
        });
        recycleview.setLayoutManager(layoutManager);
        ll_contaier = findViewById(R.id.ll_contaier);
        initFruits();
        FruitAdapter adapter = new FruitAdapter(getApplicationContext(), fruitList);
        recycleview.setAdapter(adapter);
        TextView tv_test = findViewById(R.id.tv_test);
        tv_test.setTextSize(20);
        tv_test.setText(Html.fromHtml(String.format(getResources().getString(R.string.Preferentialamount), "1")));
//        tv_test.setText(1+"");
        ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new CustomItemTouchCallback());
        itemTouchHelper.attachToRecyclerView(recycleview);
        List<Ringtone> ringtones = getRingtoneList(RingtoneManager.TYPE_NOTIFICATION);
//        Log.e("tag", ringtones.size() + "");

//        for (int i = 0; i < ringtones.size(); i++) {
//
//            Log.e("tag", ringtones.get(i).getTitle(this));
//        }

        img_shaderbg = findViewById(R.id.img_shaderbg);
        ll_test = findViewById(R.id.ll_test);
//      //1:通过图片资源文件生成Drawable实例
//        Drawable drawable = getResources().getDrawable(R.drawable.me_item_recoder_bg).mutate();
//     //2:先调用DrawableCompat的wrap方法
//        drawable = DrawableCompat.wrap(drawable);
//      //3:再调用DrawableCompat的setTint方法，为Drawable实例进行着色
//        DrawableCompat.setTint(drawable, Color.RED);
        Drawable mutate = getResources().getDrawable(R.drawable.me_item_recoder_bg);
        Rect padding = new Rect();
        mutate.getPadding(padding);
        ll_test.setBackground(mutate);
//        ll_test.setPadding(padding.left, 0, padding.left, padding.bottom);
//        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) ll_test.getLayoutParams();
//        layoutParams.leftMargin = padding.left;
//        layoutParams.rightMargin = padding.left;
//        layoutParams.bottomMargin = padding.bottom;
//        ll_test.setLayoutParams(layoutParams);
        img_photo = findViewById(R.id.img_photo);

        findViewById(R.id.btn_sys_photo).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

//             goPhotoAlbum();
                List<String> paths = PhotoUtils.getSystemPhotoList(MainActivity.this);
                for (String path : paths) {

                    Log.e("path", path);
                    Glide.with(MainActivity.this).load("path").into(img_photo);
                }
            }
        });


        List list = new ArrayList();
        list.add(2);

        Collections.sort(list, new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                int o = (int) o1;
                int i = (int) o2;
                if (o > i) {
                    return 1;
                } else if (o < i) {
                    return -1;
                }
                return 0;
            }
        });

//        alifanyi();
//        TestFanyi();
        baidufanyi();

        ImageView imageView = findViewById(R.id.img_test1);

//        imageView.setImageResource(R.drawable.abunation_list);
//        AnimationDrawable animationDrawable = (AnimationDrawable) imageView.getDrawable();
//        animationDrawable.start();

        btn_test_setY = findViewById(R.id.btn_test_setY);
        btn_test_setY.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {


                switch (event.getAction()) {

                    case MotionEvent.ACTION_DOWN:
                        mInitY = event.getRawY();
                        break;
                    case MotionEvent.ACTION_MOVE:
                        mLastMotionY = event.getRawY();
                        float detalY = mLastMotionY - mInitY;
                        mInitY = mLastMotionY;
                        Log.e("tag", "getY--->" + btn_test_setY.getY());
                        btn_test_setY.setY(btn_test_setY.getY() + detalY);
                        break;
                }


                return false;
            }
        });
    }


    private void alifanyi() {
        String body = null;

        String uuid1 = UUID.randomUUID().toString();
        String time1 = getISO8601Time(new Date());

        try {
            body = concatQueryString(getParamter(uuid1, time1));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String url = "https://mt.cn-hangzhou.aliyuncs.com/?" + body + "&Signature=" + calSign(uuid1, time1);
        Log.e("tag", "url-->" + url);
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("tag", "onFailure: ");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d("tag", "onResponse: " + response.body().string());
            }
        });
    }


    private void initFruits() {

        for (int i = 0; i < 2; i++) {
            Fruit apple = new Fruit("Apple", R.drawable.ic_launcher_background);
            fruitList.add(apple);
            Fruit banana = new Fruit("Banana", R.drawable.ic_launcher_background);
            fruitList.add(banana);
            Fruit orange = new Fruit("Orange", R.drawable.ic_launcher_background);
            fruitList.add(orange);
            Fruit watermelon = new Fruit("Watermelon", R.drawable.ic_launcher_background);
            fruitList.add(watermelon);
            Fruit pear = new Fruit("Pear", R.drawable.ic_launcher_background);
            fruitList.add(pear);
            Fruit grape = new Fruit("Grape", R.drawable.ic_launcher_background);
            fruitList.add(grape);
            Fruit pineapple = new Fruit("Pineapple", R.drawable.ic_launcher_background);
            fruitList.add(pineapple);
            Fruit strawberry = new Fruit("Strawberry", R.drawable.ic_launcher_background);
            fruitList.add(strawberry);
            Fruit cherry = new Fruit("Cherry", R.drawable.ic_launcher_background);
            fruitList.add(cherry);
            Fruit mango = new Fruit("Mango", R.drawable.ic_launcher_background);
            fruitList.add(mango);

        }
    }

    /**
     * Drawable转换成一个Bitmap
     *
     * @param drawable drawable对象
     * @return
     */
    public static final Bitmap drawableToBitmap(Drawable drawable) {
        Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(),
                drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565);
        Canvas canvas = new Canvas(bitmap);
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        drawable.draw(canvas);
        return bitmap;
    }


    public class CustomItemTouchCallback extends ItemTouchHelper.Callback {


        public CustomItemTouchCallback() {

        }

        @Override
        public int getMovementFlags(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder) {
            // 上下拖动
            int dragFlags = ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT;
            // 向左滑动
            int swipeFlags = 0;
            return makeMovementFlags(dragFlags, swipeFlags);
        }

        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
            // 交换在数据源中相应数据源的位置
            return true;
        }

        @Override
        public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
            // 从数据源中移除相应的数据
        }
    }

    List<Ringtone> getRingtoneList(int type) {

        List<Ringtone> resArr = new ArrayList<Ringtone>();
        RingtoneManager manager = new RingtoneManager(this);
        manager.setType(type);
        Cursor cursor = manager.getCursor();
        int count = cursor.getCount();
        for (int i = 0; i < count; i++) {
            resArr.add(manager.getRingtone(i));
        }
        return resArr;
    }

    //激活相册操作
    private void goPhotoAlbum() {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent, 2);
    }


    class Resource {
        String name;
        String sex;
    }

    class Input implements Runnable {
        Resource r;//确保两个类用的对象都是外面的对象。因为两个线程的锁要统一。

        Input(Resource r)//构造函数，进行初始化
        {
            this.r = r;
        }

        public void run() {
            int x = 0;
            while (true)//while不需要同步
            {
                synchronized (r)//两个类，如果都用obj，也是有两个obj。
                {
                    if (x == 0) {
                        r.name = "mike";
                        r.sex = "男";
                    } else {
                        r.name = "丽丽";
                        r.sex = "femal";
                    }
                    x = (x + 1) % 2;
                }
            }
        }
    }

    class Output implements Runnable {
        Resource r;

        Output(Resource r) {
            this.r = r;
        }

        public void run() {
            while (true)//while不需要同步
            {
                synchronized (r) {
                    System.out.println("姓名" + r.name + "性别" + r.sex);
                }
            }
        }
    }

    //    测试死锁
    private Object object1 = new Object();
    private Object object2 = new Object();


    public class MyThread1 extends Thread {

        @Override
        public void run() {
            super.run();
            synchronized (object1) {
                Log.e("TAG", "MyThread1---object1");
                SystemClock.sleep(1000);

                synchronized (object2) {
                    Log.e("TAG", "MyThread1---object2");
                    SystemClock.sleep(1000);

                }
            }
        }
    }

    public class MyThread2 extends Thread {

        @Override
        public void run() {
            super.run();
            synchronized (object2) {
                Log.e("TAG", "MyThread2---object2");
                SystemClock.sleep(1000);

                synchronized (object1) {
                    Log.e("TAG", "MyThread2---object1");
                    SystemClock.sleep(1000);

                }
            }
        }
    }


    private void TestFanyi() {

        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "123456", "123456");
        IAcsClient client = new DefaultAcsClient(profile);
        TranslateGeneralRequest request = new TranslateGeneralRequest();
        request.setSysRegionId("cn-hangzhou");
        request.setFormatType("text");
        request.setSourceLanguage("zh");
        request.setTargetLanguage("en");
        request.setSourceText("你好");


        try {
            TranslateGeneralResponse response = client.getAcsResponse(request);
            System.out.println(new Gson().toJson(response));
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
        }

    }


    public static String concatQueryString(Map<String, String> parameters) throws UnsupportedEncodingException {
        if (null == parameters) {
            return null;
        }

        StringBuilder urlBuilder = new StringBuilder("");
        for (Map.Entry<String, String> entry : parameters.entrySet()) {
            String key = entry.getKey();
            String val = entry.getValue();
            urlBuilder.append(AcsURLEncoder.encode(key));
            if (val != null) {
                urlBuilder.append("=").append(AcsURLEncoder.encode(val));
            }
            urlBuilder.append("&");
        }

        int strIndex = urlBuilder.length();
        if (parameters.size() > 0) {
            urlBuilder.deleteCharAt(strIndex - 1);
        }

        return urlBuilder.toString();
    }

    private final static String FORMAT_ISO8601 = "yyyy-MM-dd'T'HH:mm:ss'Z'";
    private final static String TIME_ZONE = "GMT";

    public static String getISO8601Time(Date date) {
        SimpleDateFormat df = new SimpleDateFormat(FORMAT_ISO8601);
        df.setTimeZone(new SimpleTimeZone(0, TIME_ZONE));
        return df.format(date);
    }


    public StringBuilder constructReuqestParms(String uuid, String time) {

        final String HTTP_METHOD = "GET";
        Map parameters = getParamter(uuid, time);

// 排序请求参数
        String[] sortedKeys = (String[]) parameters.keySet().toArray(new String[]{});
        Arrays.sort(sortedKeys);
        final String SEPARATOR = "&";
// 构造 stringToSign 字符串
        StringBuilder stringToSign = new StringBuilder();
        stringToSign.append(HTTP_METHOD).append(SEPARATOR);
        try {
            stringToSign.append(percentEncode("/")).append(SEPARATOR);

            StringBuilder canonicalizedQueryString = new StringBuilder();
            for (String key : sortedKeys) {
// 这里注意编码 key 和 value
                canonicalizedQueryString.append("&")
                        .append(percentEncode(key)).append("=")
                        .append(percentEncode((String) parameters.get(key)));
            }
// 这里注意编码 canonicalizedQueryString
            stringToSign.append(percentEncode(canonicalizedQueryString.toString().substring(1)));
            return stringToSign;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    private Map getParamter(String uuid, String time) {
        Map parameters = new HashMap();
// 输入请求参数
        parameters.put("Action", "TranslateGeneral");
        parameters.put("FormatType", "text");
        parameters.put("Scene", "general");
        parameters.put("SourceLanguage", "zh");
        parameters.put("SourceText", "你好");
        parameters.put("TargetLanguage", "en");

        parameters.put("AccessKeyId", "LTAI4G6nDAT646byoxrAJtHq");
        parameters.put("Format", "json");
        parameters.put("SignatureMethod", "HMAC-SHA1");
        parameters.put("SignatureNonce", uuid);
        parameters.put("SignatureVersion", "1.0");
        parameters.put("Version", "2018-10-12");
        parameters.put("Timestamp", time);
        return parameters;
    }


    public String calSign(String uuid, String time) {

        String stringToSign = constructReuqestParms(uuid, time).toString();
        Log.e("tag", "stringToSign--->" + stringToSign);
        // 以下是一段计算签名的示例代码
        final String ALGORITHM = "HmacSHA1";
        final String ENCODING = "UTF-8";
        String key = "W7Ka2QH9NMyYLoJsqEUQTxm2f3C7vU&";
        Mac mac = null;
        try {
            mac = Mac.getInstance(ALGORITHM);
            mac.init(new SecretKeySpec(key.getBytes(ENCODING), ALGORITHM));
            byte[] signData = mac.doFinal(stringToSign.getBytes(ENCODING));
            String signature = new String((new BASE64Encoder()).encode(signData));
            return signature;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static final String ENCODING = "UTF-8";

    private static String percentEncode(String value) throws UnsupportedEncodingException {
        return value != null ? URLEncoder.encode(value, ENCODING).replace("+", "%20").replace("*", "%2A").replace("%7E", "~") : null;
    }


    public static String concatQueryString1(Map<String, String> parameters) {
        if (null == parameters) {
            return null;
        }

        StringBuilder urlBuilder = new StringBuilder("");
        for (Map.Entry<String, String> entry : parameters.entrySet()) {
            String key = entry.getKey();
            String val = entry.getValue();
            urlBuilder.append(key);
            if (val != null) {
                urlBuilder.append("=").append(val);
            }
            urlBuilder.append("&");
        }

        int strIndex = urlBuilder.length();
        if (parameters.size() > 0) {
            urlBuilder.deleteCharAt(strIndex - 1);
        }

        return urlBuilder.toString();
    }

    private static final String TRANS_API_HOST = "https://api.fanyi.baidu.com/api/trans/vip/translate";

    public void baidufanyi() {

        String query = "中华人民共和国";

        Map paramsmap = buildParams("20200820000547811", "gWJ4tGkV43qoxDfNGJvq", query, "auto", "en");

        String params = getUrlWithQueryString(TRANS_API_HOST, paramsmap);

        String url = params;
        Log.e("tag", "url-->" + url);
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .get()
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("tag", "onFailure: " + e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d("tag", "onResponse: " + response.body().string());
            }
        });

    }

    private Map<String, String> buildParams(String appid, String securityKey, String query, String from, String to) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("q", query);
        params.put("from", from);
        params.put("to", to);

        params.put("appid", appid);

        // 随机数
        String salt = String.valueOf(System.currentTimeMillis());
        params.put("salt", salt);

        // 签名
        String src = appid + query + salt + securityKey; // 加密前的原文
        params.put("sign", MD5.md5(src));

        return params;
    }


    public static String getUrlWithQueryString(String url, Map<String, String> params) {
        if (params == null) {
            return url;
        }

        StringBuilder builder = new StringBuilder(url);
        if (url.contains("?")) {
            builder.append("&");
        } else {
            builder.append("?");
        }

        int i = 0;
        for (String key : params.keySet()) {
            String value = params.get(key);
            if (value == null) { // 过滤空的key
                continue;
            }

            if (i != 0) {
                builder.append('&');
            }

            builder.append(key);
            builder.append('=');
            builder.append(encode(value));

            i++;
        }

        return builder.toString();
    }

    /**
     * 对输入的字符串进行URL编码, 即转换为%20这种形式
     *
     * @param input 原文
     * @return URL编码. 如果编码失败, 则返回原文
     */
    public static String encode(String input) {
        if (input == null) {
            return "";
        }

        try {
            return URLEncoder.encode(input, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return input;
    }
}
